<template>
  <div class="bg-white rounded-lg shadow-sm p-4">
    <div class="flex items-center justify-center space-x-2">
      <svg class="h-5 w-5 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      <span class="text-lg font-mono text-gray-800 time-display">{{ displayTime }}</span>
    </div>
    <p class="text-sm text-gray-500 mt-1 text-center">{{ label }}</p>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 定义 props
const props = defineProps({
  label: {
    type: String,
    default: '当前时间'
  },
  format: {
    type: String,
    default: 'full' // 'full', 'time', 'date'
  },
  updateInterval: {
    type: Number,
    default: 1000 // 更新间隔，毫秒
  }
})

// 响应式数据
const displayTime = ref('')

// 定时器引用
let timer = null

// 格式化时间
const formatTime = (date) => {
  switch (props.format) {
    case 'time':
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      })
    case 'date':
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    case 'full':
    default:
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      })
  }
}

// 更新时间
const updateTime = () => {
  displayTime.value = formatTime(new Date())
}

// 组件挂载时
onMounted(() => {
  updateTime()
  timer = setInterval(updateTime, props.updateInterval)
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>